/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.faesa.acervo.view.mbeans;

import br.faesa.acervo.business.ejb.CadastroBasicoSessionBeanLocal;
import br.faesa.acervo.entity.Usuario;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author aluno.faesa
 */
@ManagedBean
@ViewScoped
public class UsuarioConsultarManagedBean implements Serializable {

    private String filtroNome;
    private List<Usuario> usuariosList;

    @EJB
    private CadastroBasicoSessionBeanLocal ejb;

    public List<Usuario> getUsuariosList() {
        return usuariosList;
    }

    public void setUsuariosList(List<Usuario> usuariosList) {
        this.usuariosList = usuariosList;
    }

    public String getFiltroNome() {
        return filtroNome;
    }

    public void setFiltroNome(String filtroNome) {
        this.filtroNome = filtroNome;
    }

    public UsuarioConsultarManagedBean() {
    }

    @PostConstruct
    public void init() {
        System.out.println("INI COnstruct");
    }

    public String onBotaoCancelarClick() {
        this.setFiltroNome(null);
        this.setUsuariosList(null);

        return null;
    }

    public String onBotaoPesquisarClick() {
        this.obterUsuarios();

        return null;
    }

    private void obterUsuarios() {
        if (this.getFiltroNome() != null && this.getFiltroNome().length() > 0) {
            this.usuariosList = ejb.ObtemUsuarios(getFiltroNome());
        } else {
            this.usuariosList = ejb.ObtemTodosUsuarios();
        }

    }

    public String deletarUsuario(Long id) {
        if (id != null && id > 0) {
            Usuario u = ejb.obterUsuario(id);

            System.out.println("uses" + u);

            usuariosList.remove(u);
            if (u != null) {
                if (ejb.deletarUsuario(u)) {
                    addMessage("Operação realizada com sucesso !!!", FacesMessage.SEVERITY_INFO);
                } else {
                    addMessage("Falha na Remoção do Objeto !!!", FacesMessage.SEVERITY_ERROR);
                }
            }
        }
        return null;
    }

    public void addMessage(String summary, FacesMessage.Severity severity) {
        FacesMessage message = new FacesMessage(severity, summary, null);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
}
